<template>
  <div id="box">
    <div id="search">
      <el-form :inline="true" :model="studentSearch" class="demo-form-inline">
        <el-form-item label="学号">
          <el-input v-model="studentSearch.searchParams.studentNo" placeholder="请输入学号"></el-input>
        </el-form-item>

        <el-form-item label="班级" prop="clazz">
          <el-select v-model="studentSearch.searchParams.clazz" placeholder="请选择班级名称" style="width: 100%">
            <el-option  :value=null>请选择班级名称</el-option>
            <el-option v-for="(clazz,index) in clazzList" :label="clazz.classNo" :key="index"
                       :value="clazz.id"></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="班级">-->
<!--          <el-input v-model="studentSearch.searchParams.claz" placeholder="请输入班级"></el-input>-->
<!--        </el-form-item>-->
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="onSearchSubmit">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-share" @click="exportStudentExcel">导出数据</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div id="header-bth">
      <el-button type="primary" size="small" icon=el-icon-circle-plus-outline @click="showAddStudent">添加
      </el-button>
      <el-button type="primary" size="small" icon=el-icon-circle-plus-outline @click="uploadDialogVisible=true">
        批量导入
      </el-button>
    </div>
    <div id="student-table">
      <el-table
          :data="tableData"
          stripe
          style="width: 100%">
        <el-table-column label="学号">
          <template slot-scope="scope">
            <span style="margin-left: 20px">{{ scope.row.studentNo }}</span>
          </template>
        </el-table-column>
        <el-table-column label="姓名">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="年龄">
          <template slot-scope="scope">
            <span>{{ scope.row.age }}</span>
          </template>
        </el-table-column>
        <el-table-column label="课程名称">
          <template slot-scope="scope">
            <span>{{ scope.row.courseName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="班级">
          <template slot-scope="scope">
            <span>{{ scope.row.className }}</span>
          </template>
        </el-table-column>
        <el-table-column label="手机号">
          <template slot-scope="scope">
            <span>{{ scope.row.tel }}</span>
          </template>
        </el-table-column>
        <el-table-column label="入学时间" width="180px">
          <template slot-scope="scope">
            <span>{{ scope.row.schoolYear }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280px">
          <template slot-scope="scope">
            <el-button
                icon="el-icon-edit"
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">
            </el-button>

            <el-popconfirm title="确定删除吗？" @confirm="deleteStudent(scope.$index, scope.row)">
              <el-button
                  slot="reference"
                  size="mini"
                  type="danger"
                  icon="el-icon-delete">
              </el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div id="nav-page">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="pageSizes"
          :page-size="studentSearch.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
    <!--添加 编辑学生信息弹窗-->
    <el-dialog :title="dialogTitle" :visible.sync="addStudentFormVisible" width="50%" @close="clearInfo">
      <el-form :model="studentForm" ref="studentInfo" :rules="studentRules" label-width="90px" size="medium">
        <el-input v-model="studentForm.id" autocomplete="off" v-show="false"></el-input>
        <el-form-item label="学号" prop="studentNo" v-if="dialogTitle=='添加学生'">
          <el-input v-model="studentForm.studentNo" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="studentForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="studentForm.age" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="tel">
          <el-input v-model="studentForm.tel" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="课程名称" prop="courseId">
          <el-select v-model="studentForm.courseId" placeholder="请选择课程名称" style="width: 100%">
            <el-option v-for="(course,index) in courseList" :label="course.courseName" :key="index"
                       :value="course.id" :disabled="!(!course.isDelete)"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="班级" prop="clazz">
          <el-select v-model.number="studentForm.clazz" placeholder="请选择班级名称" style="width: 100%">
            <el-option v-for="(clazz,index) in clazzList" :label="clazz.classNo" :key="index"
                       :value="clazz.id" :disabled="!(!clazz.isDelete)"></el-option>
          </el-select>
        </el-form-item>

<!--        <el-form-item label="班级" prop="clazz">-->
<!--          <el-input v-model="studentForm.clazz" autocomplete="off"></el-input>-->
<!--        </el-form-item>-->
        <el-form-item label="入学时间" prop="schoolYear">
          <el-date-picker
              style="width: 100%"
              v-model="studentForm.schoolYear"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择入学时间日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveOrUpdate">确 定</el-button>
      </div>
    </el-dialog>

    <!--批量导入弹窗-->
    <el-dialog title="导入学生信息" :visible.sync="uploadDialogVisible" width="27%">
      <el-upload
          drag
          class="upload-demo"
          action='#'
          name='file'
          accept=".xls,.xlsx"
          :show-file-list="false"
          :http-request="uploadFile">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
    </el-dialog>

  </div>
</template>

<script>


import {exportStudent, getCourse, importStudent, saveOrUpdateMessage, studentDelete, studentList} from "@/api/student";
import fileDownload from "js-file-download";
export default {
  name: "RoleView",
  data() {
    return {
      tableData: [],
      pageSizes: [5, 10, 15],
      total: 10,
      addStudentFormVisible: false,
      uploadDialogVisible: false, // 上传弹窗
      dialogTitle: '',
      studentForm: {},
      studentSearch: {  // 搜索数据
        limit: 5,
        page: 1,
        searchParams: {
          studentNo: "",
          clazz: ""
        }
      },
      studentRules: {
        name: [{required: true, message: '请输入姓名', trigger: 'blur'}],
        studentNo: [{required: true, message: '请输入学号', trigger: 'blur'}],
        courseId: [{required: true, message: '请选择专业', trigger: 'blur'}],
        clazz: [{required: true, message: '请输入班级名称', trigger: 'blur'}],
        age: [{required: true, message: '请输入年龄', trigger: 'blur'}],
        tel: [{required: true, message: '请选择手机号', trigger: 'blur'}],
        schoolYear: [{required: true, message: '请选择入学日期', trigger: 'blur'}]
      },
      /*添加学生对象弹出层 课程下拉选数据*/
      courseList: [],
      //学生班级下拉选数据
      clazzList: []


    }
  },
  methods: {
    // 自定义上传
    uploadFile(file) {
      // 创建表单数据对象 封装file数据
      let formData = new FormData();
      // username = tom    file.file 获取上传文件数据
      formData.append("file", file.file)
       importStudent(formData).then(response=>{
         if (response.code == 0){
           this.$message.success(response.message)
           this.uploadDialogVisible=false
           this.list()
         }
       })

    },
    // 批量导出数据
    exportStudentExcel() {
      // 借助 fileDownload工具实现文件的导出
      let studentNo = this.studentSearch.searchParams.studentNo
      let clazz = this.studentSearch.searchParams.clazz
      // fileDownload(res,new Date().getTime()+".xlsx")
      exportStudent({studentNo,clazz}).then(res=>{
        fileDownload(res,new Date().getTime()+".xlsx")
      })

    },
    // 编辑学生信息
    handleEdit(index, row) {
      this.dialogTitle = "编辑学生";
      this.addStudentFormVisible = true;

      // 渲染课程下拉选
      this.courseSelect();

      // 将row对象展开，并转换clazz类型，然后赋值给studentForm
      this.studentForm = {
        ...row,
        clazz: Number(row.clazz) // 将clazz从String转换为Number
      };

    },
    // 删除学生信息
    deleteStudent(index, row) {
      // 发送异步请求 根据id 删除学生信息
     studentDelete(row.id).then(response=>{
       if (response.code===0){
                this.$message.success(response.message)
         this.list()
       }
     })

    },
    // 添加或编辑学生信息
    saveOrUpdate() {
      this.$refs.studentInfo.validate(val=> {
        if (!val) {
          return this.$message.warning("请填写完整表单")
        }


      saveOrUpdateMessage(this.studentForm).then(response =>{
        if (response.code === 0) {
          this.$message.success(response.message)
          this.addStudentFormVisible = false;
          this.uploadDialogVisible = false;
          this.list()
        }
      })
      })
    },
    // 搜索
    onSearchSubmit() {
      this.studentSearch.page = 1
      this.list()
    },
    // 改变每页显示的条数触发
    handleSizeChange(val) {
      this.studentSearch.limit = val;
      this.list()
    },
    // 改变页码触发
    handleCurrentChange(val) {
      this.studentSearch.page = val;
      this.list()
    },
    // 显示弹出层
    showAddStudent() {
      this.dialogTitle = "添加学生"
      this.addStudentFormVisible = true
      // 渲染课程下拉选
     // this.courseSelect()
    },
    //清空校验规则
    clearInfo() {
      this.studentForm = {}
      this.$refs.studentInfo.clearValidate()
    },
    list() {
      studentList(this.studentSearch).then(response => {
        if (response.code==0){
           let{tableData,total}=  response.data
          this.total = total
          this.tableData = tableData
        }
      })

    },
    courseSelect() {
      // 课程名称下拉选异步请求
      getCourse().then(response => {
        if (response.code===0){
          let {courseList,clazzList}=  response.data
          this.courseList=courseList
          this.clazzList = clazzList
        }
      })

    }
  },
  created() {
    // 查询学生列表
    this.list()
    // 渲染课程下拉选
    this.courseSelect()

  }
}
</script>

<style scoped>

#box {
  width: 95%;
  margin: 5px auto 0;
}

#search {
  margin-top: 20px;
  padding: 5px;
  border-bottom: 1px solid #eee;
}

#header-bth {
  margin-top: 20px;
  margin-bottom: 20px;
}

#nav-page {
  margin-top: 15px;
  margin-bottom: 30px;
}

.el-button {
  margin-left: 5px;
  margin-right: 5px;
}
</style>
